let house_id = '0'
let house_index = '0'
Page({
  data: {
    dialogVisible: false,
    houseList: [],
  },
  // 每次显示时刷新更好一些
  onShow() {
    this.getHouseList()
  },
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('./room')
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败')
    // 数据渲染
    this.setData({ houseList, isEmpty: houseList.length === 0 })
  },
  swipeClose(ev) {
    const { position, instance } = ev.detail

    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })

      // 将待删除的房屋id和index保存
      house_id = ev.mark.id
      house_index = ev.mark.index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },

  goDetail(ev) {
    wx.navigateTo({
      url: `/house_pkg/pages/detail/index?id=${ev.mark.id}`,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
  async deleteHouse() {
    const { code } = await wx.http.delete('/room/' + house_id)
    if (code !== 10000) return wx.utils.toast('删除失败')
    // 删除本地houseList
    this.data.houseList.splice(house_index, 1)
    // 删除后需要进行页面更新
    this.setData({
      houseList: this.data.houseList,
    })
  },
  dialogClose(ev) {
    console.log(ev.detail)
    if (ev.detail === 'confirm') {
      return this.deleteHouse()
    }
  },
})
